package com.zhl.media.app.mvp.presenter;

import android.app.Application;
import android.widget.Toast;

import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.muddzdev.styleabletoast.StyleableToast;
import com.orhanobut.hawk.Hawk;
import com.zhl.media.app.R;
import com.zhl.media.app.event.Event;
import com.zhl.media.app.greendao.AdJustDao;
import com.zhl.media.app.greendao.MediaPositionDao;
import com.zhl.media.app.model.AdJust;
import com.zhl.media.app.model.MediaPosition;
import com.zhl.media.app.mvp.contract.MineContract;
import com.zhl.media.app.utils.EntityManager;
import com.zhl.media.commonsdk.base.BaseRespose;
import com.zhl.media.commonsdk.data.UserUtil;
import com.zhl.media.commonsdk.enumeration.MediaCode;
import com.zhl.media.commonsdk.utils.EmptyUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.inject.Inject;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@FragmentScope
public class MinePresenter extends BasePresenter<MineContract.Model, MineContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public MinePresenter(MineContract.Model model, MineContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void getUserInfo(){
        mModel.getUserInfo()
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(3, 2))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseRespose<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(BaseRespose<Map> data) {
                        mRootView.onSuccess(data.data);
                    }
                });
    }

    public void saveAbnormalInfo(){
        MediaPositionDao mediaPositionDao = EntityManager.getInstance(mApplication).getMediaPositionDao();
        AdJustDao adJustDao = EntityManager.getInstance(mApplication).getAdJustDao();
        List<AdJust> adJusts = adJustDao.loadAll();
        List<Map> list = new ArrayList<>();
        for (int i = 0; i < adJusts.size(); i++) {
            AdJust adJust = adJusts.get(i);
            if(adJust.getIsAdjust()==0){
                //如果没有调整好
                Map map = new HashMap();
                map.put("id",adJust.getId());
                map.put("mediaId",adJust.getOldMediaId());
                map.put("pushPersonId", UserUtil.getUser().getId());
                map.put("companyId",UserUtil.getUser().getCompanyId());
                map.put("pushDate", Hawk.get("thisDate"));
                map.put("pushStatus",2);
                MediaPosition unique = mediaPositionDao.queryBuilder().where(MediaPositionDao.Properties.Id.eq(adJust.getOldMediaId())).unique();
                map.put("schemeId",unique.getSchemeId());
                map.put("projectId",unique.getProjectId());
                map.put("abnormalState",adJust.getAdjustStatus());
                map.put("abnormalDescribe",adJust.getDes());
                map.put("adjustMediaId","");
                if(adJust.getAdjustStatus()==1){
                    //待调整
                    map.put("adjustState", MediaCode.DTZ.getKey());
                }
                if(adJust.getAdjustStatus()==2){
                    //需补画
                    map.put("adjustState",MediaCode.XBH.getKey());
                }
                list.add(map);
            }

            if(adJust.getIsAdjust()==1){
                //如果已经调整好

                //旧媒体位数据封装
                Map map = new HashMap();
                map.put("id",adJust.getId());
                map.put("mediaId",adJust.getOldMediaId());
                map.put("pushPersonId", UserUtil.getUser().getId());
                map.put("companyId",UserUtil.getUser().getCompanyId());
                map.put("pushDate", Hawk.get("thisDate"));
                map.put("pushStatus",2);
                MediaPosition unique = mediaPositionDao.queryBuilder().where(MediaPositionDao.Properties.Id.eq(adJust.getOldMediaId())).unique();
                map.put("schemeId",unique.getSchemeId());
                map.put("projectId",unique.getProjectId());
                map.put("abnormalState",adJust.getAdjustStatus());
                map.put("abnormalDescribe",adJust.getDes());
                map.put("adjustMediaId","");
                //已调整至新位置
                map.put("adjustState",MediaCode.WCTZ.getKey());

                //新媒体位数据封装
                Map newMap = new HashMap();
                newMap.put("id", UUID.randomUUID().toString().replace("-",""));
                newMap.put("mediaId",adJust.getNewMediaId());
                newMap.put("pushPersonId", UserUtil.getUser().getId());
                newMap.put("companyId",UserUtil.getUser().getCompanyId());
                newMap.put("pushDate", Hawk.get("thisDate"));
                newMap.put("pushStatus",2);
                MediaPosition newUnique = mediaPositionDao.queryBuilder().where(MediaPositionDao.Properties.Id.eq(adJust.getNewMediaId())).unique();
                newMap.put("schemeId",newUnique.getSchemeId());
                newMap.put("projectId",newUnique.getProjectId());
                newMap.put("abnormalState",adJust.getAdjustStatus());
                newMap.put("abnormalDescribe",adJust.getDes());
                newMap.put("adjustMediaId",adJust.getOldMediaId());
                //原异常位调整
                newMap.put("adjustState",MediaCode.YTZ.getKey());
                list.add(map);
                list.add(newMap);
            }
        }

        Map map = new HashMap();
        map.put("pushResults",list);
        map.put("pushDate",Hawk.get("thisDate"));

        mModel.saveAbnormalInfo(map)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(1, 1))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseRespose<String>>(mErrorHandler) {
                    @Override
                    public void onNext(BaseRespose<String> data) {
                        if(data.code==0){
                            UserUtil.setAdjust(false);
                            Event.postUpdateDscNum();
                        }else {
                            StyleableToast.makeText(mApplication, "操作失败!", Toast.LENGTH_LONG, R.style.mytoast).show();
                        }
                    }
                });
    }

}
